/*
 * @描述:
 * @作者: 约訂
 * @Date: 2024-10-17 14:52:54
 * @LastEditTime: 2024-11-07 16:21:01
 * @修改人员: 约訂
 */
import OSS from "ali-oss";
import dayjs from "dayjs";
const OSSCONFIG = {
  region: "oss-cn-hangzhou",
  accessKeyId: "LTAI4GGL3FkDW48WBLNAcyzf",
  accessKeySecret: "jDjsSNDvFGZF7d8xLzRwEdOJx6qRIY",
  bucket: "xigyubucket",
  // CustomeDomainName: "https://bucket.xigyu.com",
};
/**生成文件名 格式如 b5431260-861d-11ef-8d48-7b6378598a8e */
function generateUniqueFileName() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0; // 生成一个随机数
    const v = c === "x" ? r : (r & 0x3) | 0x8; // 确保符合 UUID 的版本要求
    return v.toString(16); // 转换为十六进制
  });
}

/**
 * 获取文件后缀
 * @param {*} file 文件流
 * @returns 文件后缀
 */
function getFileExtension(file: any) {
  let fileType = "";
  // 如果 file.name 存在，优先从文件名中获取后缀
  if (file.name) {
    const match = file.name.match(/\.([^.]+)$/);
    if (match) {
      return match[1]; // 返回后缀名
    }
  }
  // 如果没有文件名，使用 file.type 获取后缀
  switch (file.type) {
    case "image/jpeg":
      fileType = "jpg";
      break;
    case "image/png":
      fileType = "png";
      break;
    case "video/mp4":
      fileType = "mp4";
      break;
    case "video/flv":
      fileType = "flv";
      break;
    case "video/avi":
      fileType = "avi";
      break;
    case "video/wmv":
      fileType = "wmv";
      break;
    case "video/quicktime":
      fileType = "mov";
      break;
    default:
      fileType = "unknown";
  }
  return fileType; // 返回文件类型
}

/**
 * oss直传 上传附件
 * @param {*} fileStream 文件流
 */
export async function ossUplaod(fileStream: any, n: Function) {
  const client = new OSS(OSSCONFIG);
  try {
    const uniqueFileName = `zanCun/${dayjs().format(
      "YYYY-MM-DD"
    )}/${generateUniqueFileName()}.${getFileExtension(fileStream)}`;
    console.log("上传文件全称:", uniqueFileName);

    // 上传文件到OSS
    const result = await client.put(uniqueFileName, fileStream);
    const d = { Success: true, rows: result };
    n(d);
    return d;
  } catch (error) {
    const d = { Success: false, rows: error };
    n(d);
    return d;
  }
}
